<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/js/vue.js"></script>
    <script src="/js/axios.min.js"></script>
    <script src="/element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <el-button type="primary" @click="openDialog()">添加用户</el-button>
    <el-table
            :data="users"
            border
            style="width: 100%">
        <el-table-column
                fixed
                prop="loginAct"
                label="账户"
                width="150">
        </el-table-column>
        <el-table-column
                prop="name"
                label="姓名"
                width="120">
        </el-table-column>
        <el-table-column
                prop="email"
                label="邮箱"
                width="120">
        </el-table-column>
        <el-table-column
                prop="expireTime"
                label="失效时间"
                width="200">
        </el-table-column>
        <el-table-column
                label="锁定状态"
                width="200">
            <template slot-scope="scope">
                <div v-if="scope.row.admin!=1">
                    锁定
                    <el-switch
                            v-model="scope.row.lockState"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-value="1"
                            inactive-value="0"
                            @change="editLockState(scope.row)">
                    </el-switch>
                    正常
                </div>
                <div v-else>
                    正常
                </div>

            </template>
        </el-table-column>
        <el-table-column
                prop="admin"
                label="超级管理员"
                :formatter="formatterAdmin"
                width="120">
        </el-table-column>
        <el-table-column
                label="操作"
                width="500">
            <template slot-scope="scope">
                <div v-if="scope.row.admin!=1">
                    <el-button @click="handleClick(scope.row)" type="text" size="small">删除</el-button>
                    <el-button type="text" size="small" @click="openDialog(scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="openRoleDialog(scope.row.id)">分配角色</el-button>
                </div>
               <div v-else>
                   超级管理员禁止操作
               </div>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>
    <!--添加和修改的弹框-->
    <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
        <el-form :model="user">
            <el-form-item label="账号" :label-width="formLabelWidth">
                <el-input v-model="user.loginAct" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth">
                <el-input v-model="user.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
                <el-input v-model="user.loginPwd" show-password autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth">
                <el-input v-model="user.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="失效时间" :label-width="formLabelWidth">
                <el-date-picker
                        v-model="user.expireTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="是否是超级管理员" :label-width="formLabelWidth">
                否
                <el-switch
                        v-model="user.admin"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-value="1"
                        inactive-value="0">
                </el-switch>
                是
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveUser">确 定</el-button>
        </div>
    </el-dialog>

    <!--分配角色的弹框-->
    <el-dialog title="分配角色" :visible.sync="roleDialog">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>

        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedRoles" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in roles" :label="item.rid" :key="item.rid">{{item.roleName}}</el-checkbox>
        </el-checkbox-group>
        <div style="text-align: right">
            <el-button type="primary" @click="saveUserRole">确定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: "#app",
        data: {
            checkedRoles:[],//选中的角色的id
            isIndeterminate: false, //半选状态
            checkAll: false,//全选
            roleDialog:false,  //分配角色弹框
            roles:[],//所有的角色
            dialogFormVisible: false,
            formLabelWidth: '120px',
            user:{
                id:undefined,
                loginAct:undefined,
                name:undefined,
                loginPwd:undefined,
                email:undefined,
                /**
                 * 失效时间为空的时候表示永不失效，失效时间为2018-10-10 10:10:10，则表示在该时间之前该账户可用。
                 */
                expireTime:undefined,
                createBy:undefined,
                /**
                 * 用户ID
                 */
                editBy:undefined,
                admin:undefined,
            },
            users:[],
            pageNum:1,
            pageSize:5,
            total:undefined,
            targetUserId:undefined, //点击当前行的分配权限的id
        },
        methods: {
            saveUserRole(){//重新分配角色
                axios.put(`/role/editUserRole?userId=${this.targetUserId}&rids=${this.checkedRoles.join(",")}`)
                .then(resp=>{
                    let data=resp.data;
                    if (data.code==200){
                        this.$message({
                            type:"success",
                            message:"操作成功"
                        });
                        this.roleDialog=false
                    }
                })
            },
            handleCheckAllChange(val) {//全选事件
                // this.checkedRoles = val ? this.roles : [];
                this.checkedRoles=[];//选中的id
                if (val){//全选
                    this.roles.forEach(item=>{
                        this.checkedRoles.push(item.rid)
                    })
                }
                this.isIndeterminate = false;
            },
            handleCheckedCitiesChange(value) {//单选事件
                let checkedCount = value.length;
                //全选状态
                this.checkAll = checkedCount === this.roles.length;
                //半选 == > 至少选中一个并且没有全选
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
            },
            openRoleDialog(userid){//分配角色的弹框
              this.roleDialog=true;
              this.targetUserId=userid;
              //获取所有的角色
              axios.get("/role?pageSize=100000").then(resp=>{
                  let data=resp.data;
                  this.roles=data.result
              });
              //根据用户id查询已有的角色,并且打钩
             axios.get(`/role/getRoleIdsByUserId?userId=${userid}`).then(resp=>{
                 let data=resp.data;
                 this.checkedRoles=data.result;
             })
            },
            saveUser(){
              axios({
                  method:this.user.id?"put":"post",
                  url:"/user",
                  data:this.user
              }).then(resp=>{
                  let data=resp.data;
                  if (data.code==200){
                      this.$message({
                          type:"success",
                          message: "操作成功"
                      });
                      this.dialogFormVisible=false;
                      //刷新数据
                      this.initData();
                  }else{
                      this.$message({
                          type:"error",
                          message: data.msg
                      });
                  }
              })
            },
            openDialog(item){
                let loginUser=JSON.parse(sessionStorage.getItem("user"));
                this.dialogFormVisible=true;
                if (item){//修改
                    this.user={...item}
                    this.user.editBy=loginUser.id
                }else{//添加
                    this.user={
                        id:undefined,
                        loginAct:undefined,
                        name:undefined,
                        loginPwd:undefined,
                        email:undefined,
                        /**
                         * 失效时间为空的时候表示永不失效，失效时间为2018-10-10 10:10:10，则表示在该时间之前该账户可用。
                         */
                        expireTime:undefined,
                        createBy:undefined,
                        /**
                         * 用户ID
                         */
                        editBy:undefined,
                        admin:undefined,
                    }
                    //设置创建人
                    this.user.createBy=loginUser.id;
                }
            },
            formatterAdmin(row, column){//格式化类列的显示内容
                // console.log(row,column)
                return row.admin==1?"超级管理员":"普通用户"
            },
            editLockState(val){//根据主键修改锁定状态
                // console.log(val)
                axios.put(`/user/editLockStateById?id=${val.id}&state=${val.lockState}`)
                .then(resp=>{
                    let data=resp.data;
                    if (data.code==200){
                        this.$message({
                            type:"success",
                            message:"操作成功"
                        })
                    }
                })
            },
            initData(){//初始化表格数据
                axios.get("/user/page",{params:{
                        pageNum:this.pageNum,
                        pageSize: this.pageSize
                    }}).then(resp=>{
                        let data=resp.data;
                        this.users=data.result;
                        this.total=data.count;
                })
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize=val;
                this.initData()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum=val;
                this.initData()
            }
        },
        created(){
            this.initData();
        }
    })
</script>
</body>
</html>